/*
 * This file is part of aKoustiK.

 * aKoustiK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * aKoustiK is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with aKoustiK.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <QtCore/QTimer>

#include <KGlobal>
#include <KSharedConfig>
#include <KSharedConfigPtr>
#include <KStandardDirs>

#include <kore.h>
#include <playlist.h>
#include <storage/internalstorage.h>
#include <storage/xspfstorage.h>

void InternalStorage::store(Playlist* playlist) {
    InternalStorage* worker = new InternalStorage(playlist);
    QTimer::singleShot(0, worker, SLOT(exec()));
}

void InternalStorage::exec() {
    QString currentPlaylist = KGlobal::config()->group("Playlist").readEntry("current", QString());
    if (currentPlaylist.isNull() || currentPlaylist.isEmpty()) {
        currentPlaylist = "Current.xspf";
        KGlobal::config()->group("Playlist").writeEntry("current", currentPlaylist);
    }
    QString playlistPath = KStandardDirs::locateLocal("appdata", "playlists/" + currentPlaylist, true);
    XspfStorage storage(playlistPath);
    storage.setName(playlist->name());
    storage.setItems(playlist->items());
    storage.store();
    // work done, scheduling self for deletion:
    deleteLater();
}

Playlist* InternalStorage::loadCurrentPlaylist() {
    // TODO move this loading to background thread
    QString currentPlaylist = KGlobal::config()->group("Playlist").readEntry("current", QString());
    qDebug() << "InternalStorage: saved playlist: " << currentPlaylist;
    if (currentPlaylist.isNull() || currentPlaylist.isEmpty()) {
        Playlist* playlist = new Playlist(QList<Item*>(), "Current", &(Kore::instance()));
        InternalStorage::store(playlist);
        return playlist;
    }
    // if we are still here - we have some playlist saved:
    QString playlistPath = KStandardDirs::locateLocal("appdata", "playlists/" + currentPlaylist);
    XspfStorage storage(playlistPath);
    storage.load();
    return new Playlist(storage.items(), storage.name(), &(Kore::instance()));
}

InternalStorage::InternalStorage(Playlist* targetPlaylist) : QObject(), playlist(targetPlaylist) {
}

InternalStorage::~InternalStorage() {
}
